import jwt from 'jsonwebtoken';
import {config} from "../config/index.js";
import tokenRoles from "../roleType/tokenRoles.js";
import {checkInviterCode} from "../controllers/user.js";

let jwtKey = config.JWT_KEY;
// 不需要权限校验的请求
const non_auth_req = {
  '/user/register': true,
  '/user/login': true,
  '/user/checkdata': true,
  '/user/checkcode': true,
  '/user/getemail': true,
  '/user/verifyPassword': true,
  '/captcha/*': true,
  '/token/checkToken': true,
  '/test': true
};

function validateString(str) {
  if(non_auth_req[str]){
    return true;
  }
  for (const route in non_auth_req) {
    const regex = new RegExp(`^${route.replace('*', '.*')}$`);
    if (regex.test(str)) {
      return true;
    }
  }
  return false;
}

// 请求拦截进行token验证
export const authToken = async (req, res, next) => {
  // 跨域请求不做验证
  if (req.method === 'OPTIONS') {
    next();
    return;
  }
  // 检查是否需要验证权限
  // console.log(req.url, validateString(req.url));
  if (validateString(req.url)) {
    next();
    return;
  }
  // 验证token
  if (!req.headers['authorization']) {
    throw new Error("请重新登录账号");
  }
  const token = req.headers['authorization'].split(" ")[1];
  let user_id = req.headers['authorization'].split(" ")[2];
  const tokenResult = await verifyToken(token, (data) => {
    // console.log(data);
    if (Number(data.id) !== Number(user_id)) {
      return false;
    }
    // 验证用户类型
    // 0 普通用户 1 管理员
    // 管理员可以访问所有接口
    if (data.type === tokenRoles.ADMIN) {
      return true;
    }
    // 普通用户只能访问普通用户接口
    if (data.type === tokenRoles.USER && req.url.startsWith('/user/')) {
      return true;
    }
    // 刷新token
    if (data.type === tokenRoles.TOKEN && req.url.startsWith('/token/')) {
      return true;
    }
    // 其他情况验证失败
    return false;
  });

  if (!tokenResult) {
    throw new Error("请重新登录账号。");
    return;
  }
  next();
};

/**
 * 创建token 默认3天=72h 还有15天=360h data默认包含id和type
 * @param data
 * @param time
 * @returns {Promise<unknown>}
 */
export const createToken = (data, time = "72h") => {
  return new Promise((resolve, reject) => {
    jwt.sign(
      data,
      jwtKey,
      {expiresIn: time},
      (err, token) => {
        if (err) {
          reject(err);
        }
        resolve(token);
      }
    );
  });
};

export const createRoleToken = async (id, tokenType = tokenRoles.USER) => {
  const token = await createToken({id: Number(id), type: tokenType});
  const refreshToken = await createToken({id: Number(id), type: tokenRoles.TOKEN}, "360h");
  return {
    token,
    refreshToken,
    result: true
  };
};

// 验证token id一致且没到期
export const verifyToken = async (token, verifyFunc) => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, jwtKey, (err, decoded) => {
      if (err || !verifyFunc(decoded)) {
        resolve(false);
      } else {
        resolve(true);
      }
    });
  });

};
